package com.example.webrestfulcrud.config;

import com.example.webrestfulcrud.component.MyInterceptor;
import com.example.webrestfulcrud.component.MyLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;

/**
 * 使用WebMvcConfigurer可以扩张SpringMvc的功能
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    //不能添加Bean注解 @Bean
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        /**
         * 这样可以发送一个/nihao 请求，可以跳转 success.html页面
         * 就没必要单独的为success添加一个Controller了
         *
         * @GetMapping("/nihao")
         * public String page(){
         *      return "success";
         * }
         */
        registry.addViewController("/nihao").setViewName("success");

    }

    /**
     * 因为所有的WebMvcConfigurer都会一起起作用(需要先创建该对象，@Bean)，所以还有第二种配置方式
     * 因为 DelegatingWebMvcConfiguration 类中的这个方法
     *
     * @return
     * @Autowired(required = false) //从容器中获取所有的WebMvcConfigurer
     * public void setConfigurers(List<WebMvcConfigurer> configurers) {
     * if (!CollectionUtils.isEmpty(configurers)) {
     * this.configurers.addWebMvcConfigurers(configurers);
     * }
     * }
     */
    @Bean   //前提是该组件在容器中
    public WebMvcConfigurer indexPage() {
        return new WebMvcConfigurer() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("login.html").setViewName("login");
                registry.addViewController("/").setViewName("login");
            }

            // 注册拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                /*registry.addInterceptor(new MyInterceptor()).excludePathPatterns(
                        Arrays.asList(
                                new String[]{
                                        "/", "/login.html","/user/login","/asserts/**"
                                }
                        )
                );*/
            }
        };
    }

    /**
     * 不可以更改方法名
     *
     * @return
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }

    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
        return new HiddenHttpMethodFilter();
    }
}
